from typing import List, Optional
from fastapi import HTTPException, Depends
from sqlalchemy.orm import Session
from app.models.order import Order, OrderCreate, OrderUpdate, OrderModel, OrderItemModel, OrderStatus
from app.models.item import ItemModel
from app.database.database import Database
from app.config.database import get_db
from app.config.logger import logger
import uuid

class OrderService:
    def __init__(self, db: Session):
        self.db = Database(db)

    def create_order(self, order: OrderCreate) -> Order:
        # 生成订单号
        order_number = f"ORD-{uuid.uuid4().hex[:8].upper()}"
        
        # 创建订单
        db_order = OrderModel(
            user_id=order.user_id,
            order_number=order_number,
            total_amount=order.total_amount,
            status=order.status
        )
        self.db.add(db_order)
        self.db.flush()  # 获取订单ID

        # 创建订单项
        for item in order.items:
            # 检查商品是否存在
            db_item = self.db.query(ItemModel).filter(ItemModel.id == item.item_id).first()
            if not db_item:
                raise HTTPException(status_code=404, detail=f"Item {item.item_id} not found")
            
            # 检查库存
            if db_item.stock < item.quantity:
                raise HTTPException(status_code=400, detail=f"Insufficient stock for item {item.item_id}")
            
            # 创建订单项
            order_item = OrderItemModel(
                order_id=db_order.id,
                item_id=item.item_id,
                quantity=item.quantity,
                price=item.price
            )
            self.db.add(order_item)
            
            # 更新库存
            db_item.stock -= item.quantity

        self.db.commit()
        self.db.refresh(db_order)
        return db_order

    def get_order(self, order_id: int) -> Order:
        order = self.db.query(OrderModel).filter(OrderModel.id == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")
        return order

    def get_user_orders(self, user_id: int) -> List[Order]:
        return self.db.query(OrderModel).filter(OrderModel.user_id == user_id).all()

    def update_order_status(self, order_id: int, status: OrderStatus) -> Order:
        order = self.get_order(order_id)
        order.status = status
        self.db.commit()
        self.db.refresh(order)
        return order

    def cancel_order(self, order_id: int) -> Order:
        order = self.get_order(order_id)
        
        # 只能取消待支付的订单
        if order.status != OrderStatus.PENDING:
            raise HTTPException(status_code=400, detail="Can only cancel pending orders")
        
        # 恢复库存
        for item in order.items:
            db_item = self.db.query(ItemModel).filter(ItemModel.id == item.item_id).first()
            if db_item:
                db_item.stock += item.quantity
        
        # 更新订单状态
        order.status = OrderStatus.CANCELLED
        self.db.commit()
        self.db.refresh(order)
        return order

def get_order_service(db: Session = Depends(get_db)) -> OrderService:
    return OrderService(db) 